const fs = require("fs");
const archiver = require("archiver");
let config = {
  ignore: [
    "node_modules",
    "package-lock.json",
    "README.md",
    "compress-directory.js",
    "build",
    "references",
    ".git",
    ".gitignore",
    ".vscode",
    ".editorconfig",
    ".eslintrc.json",
    "牙叔教程q群.png",
    "牙叔教程公众号.jpg",
    ".autojs.sync.ignore",
    "1.js",
    "build.zip",
  ],
};
let { dirs, files } = walk(".");
console.log(dirs);
console.log(files);

const output = fs.createWriteStream("build.zip");
const archive = archiver("zip", { zlib: { level: 9 } });
archive.on("error", function (err) {
  throw err;
});

archive.pipe(output);
dirs.forEach((item) => {
  archive.directory(item, item);
});
files.forEach((item) => {
  archive.file(item, { name: item });
});
archive.finalize();

/* -------------------------------------------------------------------------- */
function walk(path) {
  let children = fs.readdirSync(path);
  let dirs = [];
  let files = [];
  children.forEach(function (item, index) {
    let fPath = path + "/" + item;
    let stat = fs.statSync(fPath);
    if (stat.isDirectory() === true) {
      dirs.push(fPath);
    }
    if (stat.isFile() === true) {
      files.push(fPath);
    }
  });
  dirs = dirs.map((item) => item.replace("./", ""));
  files = files.map((item) => item.replace("./", ""));
  dirs = dirs.filter((item) => config.ignore.indexOf(item) < 0);
  files = files.filter((item) => config.ignore.indexOf(item) < 0);
  return {
    dirs: dirs,
    files: files,
  };
}
